<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { addJueSeApi } from '@/api/system'
import { userStatus } from '@/views/system/dictionary'
import { usetreeStore } from '@/stores/index'
import { convertTree } from '@/utils/publicMethods'
import type Node from 'element-plus/es/components/tree/src/model/node'

const props = defineProps<{
  isShow: boolean
  title: string
  formInfo: any
}>()

const treeStore = usetreeStore()
const regionTreeArry = JSON.parse(JSON.stringify(convertTree(treeStore.regionTreeList)))
const regionTreeFn = (node: Node, resolve: (data: any[]) => void) => {
  // 树形结构地域
  if (node.level === 0) {
    const info = regionTreeArry.map((item: any) => {
      return {
        value: item.value,
        label: item.label,
        children: item.children
      }
    })
    return resolve(info)
  }

  if (node.level > 1) {
    if (!node.data.children) {
      node.data.children = []
    } else {
      setTimeout(() => {
        const data = node.data.children
        resolve(data)
      }, 100)
    }
  }
  setTimeout(() => {
    const data = node.data.children
    resolve(data)
  }, 100)
}
const huaXiaoTreeArry = JSON.parse(JSON.stringify(convertTree(treeStore.huaXiaoTreeList)))
const huaXiaoTreeFn = (node: Node, resolve: (data: any[]) => void) => {
  // 树形结构地域
  if (node.level === 0) {
    const info = huaXiaoTreeArry.map((item: any) => {
      return {
        value: item.value,
        label: item.label,
        children: item.children
      }
    })
    return resolve(info)
  }

  if (node.level > 1) {
    if (!node.data.children) {
      node.data.children = []
    } else {
      setTimeout(() => {
        const data = node.data.children
        resolve(data)
      }, 500)
    }
  }
  setTimeout(() => {
    const data = node.data.children
    resolve(data)
  }, 500)
}

const emit = defineEmits<{
  (e: 'update:isShow', value: boolean): void
  (e: 'getYongHuData'): void
}>()

const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  user_id: string
  user_name: string
  password: string
  region_id: string
  region_name: string
  hx_number: string
  hx_name: number
  telephone: string
  email: string
  state: string
}

const form = ref<any>({
  exist: 0,
  user_id: '',
  user_name: '',
  password: '',
  region_id: '',
  region_name: '',
  hx_number: '',
  hx_name: '',
  telephone: '',
  email: '',
  state: ''
})

if (props.title === '修改角色') {
  form.value = { ...props.formInfo }
  form.value.password = ''
  form.value.region_id = [form.value.region_id]
  form.value.hx_number = [form.value.hx_number]
  form.value.state = Number(form.value.state)
}

const RefreshForm = ref({
  exist: 0,
  user_id: '',
  user_name: '',
  password: '',
  region_id: '',
  region_name: '',
  hx_number: '',
  hx_name: '',
  telephone: '',
  email: '',
  state: ''
})

// 获得树节点
const getRegionTreeNode = (node: any) => {
  if (form.value.region_id.length > 0) {
    form.value.region_name = node.label
  }
}

const getHuaXiaoTreeNode = (node: any) => {
  if (form.value.hx_number.length > 0) {
    form.value.hx_name = node.label
  }
}

const rules = reactive<FormRules<RuleForm>>({
  user_id: [{ required: true, message: '请输入角色ID', trigger: 'blur' }],
  user_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入备注', trigger: 'blur' }],
  region_id: [{ required: true, message: '请选择所属区域', trigger: 'blur' }],
  hx_number: [{ required: true, message: '请选划小名称', trigger: 'blur' }],
  telephone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '请输入正确的邮箱',
      trigger: 'blur'
    }
  ],
  state: [{ required: true, message: '请选择状态', trigger: 'blur' }]
})

const addYongHuBoxFn = async () => {
  const {
    user_id,
    user_name,
    password,
    region_id,
    region_name,
    hx_number,
    hx_name,
    telephone,
    email,
    state,
    exist
  } = form.value
  const sqlIdInfo = props.title === '添加角色' ? 'userMgr.insertUser' : 'userMgr.updateUser'
  const msg = props.title === '添加角色' ? '添加' : '修改'
  const params = {
    sqlId: JSON.stringify([sqlIdInfo]),
    sqlParam: JSON.stringify([
      {
        exist,
        user_id,
        user_name,
        password,
        region_id: region_id[0],
        region_name,
        hx_number: hx_number[0],
        hx_name,
        telephone,
        email,
        state
      }
    ]),
    dbName: undefined
  }
  await addJueSeApi(params)
    .then((res: any) => {
      // console.log(res)
      if (res === 'success') {
        ElMessage({ message: msg + '成功', type: 'success' })
        emit('getYongHuData')
        emit('update:isShow', false)
      } else {
        ElMessage({ message: msg + '添加失败', type: 'error' })
      }
    })
    .catch(() => {
      ElMessage({ message: '操作失败', type: 'error' })
    })
}
const Confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      addYongHuBoxFn()
      form.value = RefreshForm.value
    } else {
      ElMessage({ message: '请输入完整信息', type: 'error' })
    }
  })
}
const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  form.value = RefreshForm.value
  emit('update:isShow', false)
}
</script>

<template>
  <div class="addYongHuBox">
    <el-dialog :model-value="true" :title="title" width="500" @close="Cancel(ruleFormRef)">
      <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="auto">
        <el-form-item label="用户ID" prop="user_id">
          <el-input
            v-model="form.user_id"
            :disabled="title === '修改角色' ? true : false"
            placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model="form.user_name" placeholder="请输用户名" />
        </el-form-item>
        <el-form-item v-if="title === '添加角色'" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输密码" />
        </el-form-item>
        <el-form-item v-else label="密码">
          <el-input v-model="form.password" placeholder="请输密码" />
        </el-form-item>
        <el-form-item label="地域名称：" prop="region_id">
          <el-tree-select
            lazy
            :load="regionTreeFn"
            :cache-data="regionTreeArry"
            v-model="form.region_id"
            multiple
            :multiple-limit="1"
            node-key="value"
            :render-after-expand="false"
            style="width: 240px"
            check-strictly
            check-on-click-node
            @check="getRegionTreeNode"
          />
        </el-form-item>
        <el-form-item label="划小名称：" prop="region_id">
          <el-tree-select
            lazy
            :load="huaXiaoTreeFn"
            v-model="form.hx_number"
            :data="huaXiaoTreeArry"
            multiple
            :multiple-limit="1"
            node-key="value"
            :render-after-expand="false"
            style="width: 240px"
            check-strictly
            check-on-click-node
            @check="getHuaXiaoTreeNode"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" clearable placeholder="请选择状态" style="width: 240px">
            <el-option
              v-for="item in userStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="Confirm(ruleFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less"></style>
